#include "netcli.hpp"
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

netcli::netcli(char* ip, int port)
{
    int ret = 0;
    struct sockaddr_in serv_addr_in;

    strcpy(ser_ip, ip);
    ser_port = port;

    cli_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (cli_fd < 0) {
        std::cerr << "Could not create socket" << std::endl;
    }

    serv_addr_in.sin_family = AF_INET;
    serv_addr_in.sin_port = htons(ser_port);

    // 将 IPv4 地址从文本转换为二进制形式
    if (inet_pton(AF_INET, ser_ip, &serv_addr_in.sin_addr) <= 0) {
        std::cout << "\nInvalid address/ Address not supported \n";
        return;
    }

    // 连接到服务器
    if (connect(cli_fd, (struct sockaddr*)&serv_addr_in, sizeof(serv_addr_in)) < 0) {
        std::cout << "\nConnection Failed \n";
        return;
    }
}

netcli::~netcli()
{
    close(cli_fd);
}

int netcli::netsend(char* buf, int len)
{
    int ret = 0;
    struct sockaddr_in ser_addr;

    memset(&ser_addr, 0, sizeof(struct sockaddr_in));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(ser_port);
    ret = inet_pton(AF_INET, ser_ip, &ser_addr.sin_addr);
    if (ret < 0) {
        std::cerr << "Invalid address/ Address not supported" << std::endl;
        return -1;
    }

    ret = sendto(cli_fd, (const char*)buf, len, MSG_CONFIRM, (const struct sockaddr*)&ser_addr, sizeof(ser_addr));
    if (ret < 0) {
        std::cerr << "Send failed" << std::endl;
        return -1;
    }

    return 0;
}

int netcli::netrecv(char* buf, int size)
{
    int ret = 0;
    socklen_t len = 0;
    struct sockaddr_in ser_addr;

    len = sizeof(struct sockaddr_in);
    ret = read(cli_fd, buf, size);
    if (ret < 0) {
        std::cerr << "Read failed" << std::endl;
        return 1;
    }
    buf[ret] = '\0';

    return 0;
}
